<template>
    <div class="tableList">
        <el-table :data="tableData" border style="width: 100%;" @sort-change="handleSortChange"
            :header-cell-style="{background:'#fafafa',color:'#000',fontWeight:400,fontSize:'12px'}"
            :cell-style="{color:'#5a5a5a',fontSize:'12px',fontWeight:400,padding:'5px 0'}" v-loading="loading" element-loading-text="加载中"
            element-loading-background="rgba(250, 250, 250, 0.5)" element-loading-spinner="el-icon-loading" :row-key="getRowKeys"
            @selection-change="handleSelectionChange" ref="tabList" :key="toUpdateTableKey">
            <el-table-column type="selection" width="55" :selectable='selectable' :reserve-selection='true'>
            </el-table-column>
            <el-table-column v-for="(item,index) in tableGroup" :key="item.label" :label="item.name"
                :sortable="item.sortable" :min-width="item.width" show-overflow-tooltip>
                <template slot-scope="scope">
                    <code v-if="item.label == 'workOrderCode'">
                        <span :style="{color:scope.row.verifyState === 0 ? 'rgb(255, 59, 48)' : 'rgb(2, 185, 128)'}">{{scope.row[item.label]}}</span>
                    </code>
                    <code v-else-if="item.label == 'processState'">
                        {{state[scope.row[item.label]]}}
                    </code>
                    <code v-else-if="item.label == 'pricingMethod'">
                        {{scope.row[item.label] == 0 ? '计件' : '计时'}}
                    </code>
                    <code v-else-if="item.label == 'verifyState'">
                        {{scope.row[item.label] == 0 ? '未审批' : '已审批'}}
                    </code>
                    <code v-else>
                        <code v-if='customImgSet(item.label, scope.row)'>
                            <p v-if='(JSON.parse(scope.row[item.label])).length <= 2'>
                                <img :src="$global.uploadUrl + k.url" alt=""
                                    v-for="(k, i) in JSON.parse(scope.row[item.label])" :key="i" class="customImg"
                                    @click='costomImgPreview(i+1, (JSON.parse(scope.row[item.label])).length, JSON.parse(scope.row[item.label]))'>
                            </p>
                            <p v-else>
                                <img :src="$global.uploadUrl + JSON.parse(scope.row[item.label])[0].url"
                                    alt="" class="customImg"
                                    @click='costomImgPreview(1, JSON.parse(scope.row[item.label]).length, JSON.parse(scope.row[item.label]))'>
                                <span class='customImgMoreBox'>
                                    <div class='customImgMore'
                                        @click='costomImgPreview(2, JSON.parse(scope.row[item.label]).length, JSON.parse(scope.row[item.label]))'>
                                        <el-popover placement="top" max-width="400" trigger="hover">
                                            <div class='customImgMore' slot="reference">
                                                +{{ JSON.parse(scope.row[item.label]).length - 2 }}</div>
                                            <img :src="$global.uploadUrl + k.url" alt=""
                                                v-for="(k, i) in JSON.parse(scope.row[item.label])" :key="i"
                                                style="margin-right:10px" width='60px' height='60px'
                                                @click="costomImgPreview(i+1, JSON.parse(scope.row[item.label]).length, JSON.parse(scope.row[item.label]))">
                                        </el-popover>
                                    </div>
                                    <img :src="$global.uploadUrl + JSON.parse(scope.row[item.label])[1].url"
                                        alt="" class="customImg">
                                </span>
                            </p>
                        </code>
                        <code v-else>
                            <code v-if="customSelectSet(item.label, scope.row)">
                                <span v-for="(k, j) in customSelectList(item.label, scope.row)" :key="j"
                                    :style="customSelectStyle(item.label, scope.row, k)" class="customSelect">
                                    {{ k }}
                                </span>
                            </code>
                            <code v-else>
                                {{scope.row[item.label]}}
                            </code>
                        </code>
                    </code>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="100">
                <template slot-scope="scope">
                    <el-button @click="watch(scope.row.id,scope.row.workOrderCode)" type="text" size="small" style="padding:0">查看
                    </el-button>
                    <el-button type="text" size="small" 
                        @click="edit(scope.row.id,scope.row.processCode,scope.row.workOrderCode)" 
                            style="padding:0">编辑</el-button>
                    <el-popconfirm
                        placement='top'
                        confirm-button-text='确认'
                        @confirm='confirmDel(scope.row.id)'
                        title="确认删除报工？删除后不可恢复!"
                        >
                        <el-button slot="reference" type="text" size="small" :disabled="!scope.row.handleState" style="padding:0">删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
            <div slot="empty">
                <el-empty :image-size='100'></el-empty>
            </div>
        </el-table>
        <el-pagination
            v-if="tableData.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="[10,20,50,100]"
            :page-size="searchForm.limit"
            layout="total,prev, pager, next,sizes,jumper"
            :total="total"
            background
            :current-page="currentPage">
        </el-pagination>
        <el-dialog :title="customImgData.title" :visible.sync="customImgData.visible" width='68%'>
            <el-carousel trigger="click" height="50vh" :autoplay='false' :initial-index='customImgData.initial'
                @change='handleCarousel' ref='carousel'>
                <el-carousel-item v-for="(item, i) in customImgData.list" :key="i">
                    <img :src="item.url" alt="" class='carouselImg'>
                </el-carousel-item>
            </el-carousel>
            <div class='imgDownLoad' @click='imgDownLoad'>
                <span class='el-icon-download'></span>
                下载
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {
        workReportList,
        workReportDel,
        updateState,
        flashPerformance
    } from '@/api/produceController'
    import {exportTable} from "@/mixin"
    export default {
        data() {
            return {
                tableData: [],
                toUpdateTableKey:false,
                loading: false,
                multipleSelection: [],
                total: 0,
                currentPage: 1,
                state: {
                    0:  '未开始',
                    1: '执行中',
                    2: '已结束',
                    3: '已取消',
                },
                customImgData: {
                    visible: false,
                    list: [],
                    title: '',
                    initial: 0,
                    num: 0
                }
            }
        },
        props: {
            tableGroup: {
                type: Array,
                default: () => []
            },
            searchForm: {
                type: Object,
                default: () => ({})
            }
        },
        mixins:[exportTable],
        methods: {
            //报工列表
            getWorkReportList(data) {                
                this.currentPage = data.page
                this.loading = true                
                workReportList(data).then(res => {
                    if (res.code == 200) {
                        this.tableData = res.data.listData.records
                        this.total = res.data.listData.total
                        this.tableData.map((item, i) => {
                            item.index = (res.data.listData.current - 1) * 10 + (i + 1)
                            if (item.customFieldVos != null) {
                                item.customFieldVos.map(k => {
                                    item[k.customFieldId] = k.value,
                                    item.customType = k.customFieldMess.fieldType
                                })
                            }
                        })
                    }
                    this.loading = false                    
                    this.$emit('getTotal',res.data.listData.total)
                    this.$emit('getSecondGroupInfo',{
                        key:res.data.secondGroupColumnName,
                        typeCountData:res.data.typeCountData
                    })
                })
            },

            //报工删除
            getWorkReportDel(data) {
                workReportDel(data).then(res => {
                    if (res.code == 200) {
                        let toggleIndex = this.multipleSelection.findIndex(i => i.id == data.id)
                        toggleIndex != -1 && this.multipleSelection.splice(toggleIndex,1)
                        if(!this.multipleSelection.length) this.$refs.tabList.clearSelection()
                        this.getWorkReportList(this.searchForm)
                        this.utils.showMsg('删除成功','success')
                    }
                })
            },
            getRowKeys(row) {
                return row.id
            },
            handleSortChange({
                order,
                prop
            }) {},
            handleSelectionChange(selection) {
                this.multipleSelection = selection
                let ids = ''
                ids = selection.map(i => i.id).toString()
                this.$emit('getCheckedId', ids)
            },
            //查看
            watch(id,code){
                this.$store.commit('setPage', this.searchForm.page);
                this.$store.commit('setRouter', this.$route.path);
                this.$router.push({
                    path:'/productionManagement/jobBooking/detail',
                    query:{
                        id,
                        code
                    }
                })
            },
            //编辑
            edit(id,code,workCode){
                this.$store.commit('setPage', this.searchForm.page);
                this.$store.commit('setRouter', this.$route.path);
                this.$router.push({
                    path:'/productionManagement/jobBooking/edit',
                    query:{
                        id,
                        code,
                        workCode
                    }
                })
            },
            selectable(row){
                if(!row.handleState){
                    return false
                }else{
                    return true
                }
            },
            //批量审批
            getUpdateState(data) {
                updateState(data).then(res => {
                    if (res.code == 200) {
                        this.getWorkReportList(this.searchForm)
                        this.$refs.tabList.clearSelection()
                        this.utils.showMsg('审批成功','success')
                    }
                })
            },
            //批量刷新绩效
            getFlashPerformance(data) {
                flashPerformance(data).then(res => {
                    if (res.code == 200) {
                        this.getWorkReportList(this.searchForm)
                        this.$refs.tabList.clearSelection()
                        this.utils.showMsg('刷新成功','success')
                    }
                })
            },
            //删除
            confirmDel(id){
                this.getWorkReportDel({id})
                let totalPage = Math.ceil((this.total - 1) / this.searchForm.limit)
                let currentPage = this.searchForm.page > totalPage ? totalPage : this.searchForm.page
                this.searchForm.page = currentPage < 1 ? 1 : currentPage
            },
            // 自定义字段 复选框/单选框 列
            customSelectSet(t, d) {
                let state = false
                if (d.customFieldVos != null) {
                    d.customFieldVos.map(item => {
                        if (item.customFieldMess != null) {
                            if ((item.customFieldMess.fieldType == 'selectRadio' || item.customFieldMess
                                    .fieldType == 'selectChecked') && t == item.customFieldId) {
                                state = true
                            }
                        }
                    })
                    return state
                } else {
                    return false
                }
            },
            customSelectList(t, d) {
                if (d[t] == '' || d[t] == '[]') {
                    return []
                } else {
                    let data = []
                    try {
                        data = JSON.parse(d[t])
                    } catch {
                        data = d[t].split(',')
                        data[0] == '' ? data = [] : ''
                    }
                    data === Number(data) ? data = [data] : ''
                    return data
                }
            },
            customSelectStyle(t, d, v) {
                let style = {}
                if (d.customFieldVos != null) {
                    let obj = d.customFieldVos.find(res => {
                        return res.customFieldId == t
                    })
                    if (obj.value != '' && obj.value != '[]') {
                        if (obj.customFieldMess.fieldType == 'selectRadio') {
                            let color = JSON.parse(obj.customFieldMess.checkBox).find(res => {
                                return obj.value == res.value
                            })
                            if (color != undefined) {
                                return {
                                    color: color.color,
                                    background: (color.color).substr(0, 3) + 'a' + (color.color).substr(3, color.color
                                        .length - 4) + ', .1)'
                                }
                            } else {
                                return {
                                    color: '#333',
                                    background: '#f4f4f5'
                                }
                            }
                        }
                        if (obj.customFieldMess.fieldType == 'selectChecked') {
                            let color = JSON.parse(obj.customFieldMess.checkBox).find(res => {
                                return v == res.value
                            })
                            if (color != undefined) {
                                return {
                                    color: color.color,
                                    background: (color.color).substr(0, 3) + 'a' + (color.color).substr(3, color.color
                                        .length - 4) + ', .1)'
                                }
                            } else {
                                return {
                                    color: '#333',
                                    background: '#f4f4f5'
                                }
                            }
                        }
                    }
                }
            },
            // 自定义字段图片列
            customImgSet(t, d) {
                let state = false
                if (d.customFieldVos != null) {
                    d.customFieldVos.map(item => {
                        if (item.customFieldMess != null) {
                            if (item.customFieldMess.fieldType == 'picture' && t == item.customFieldId) {
                                state = true
                            }
                        }
                    })
                    return state
                } else {
                    return false
                }
            },
            // 自定义图片预览
            costomImgPreview(i, len, list) {
                this.customImgData.visible = true
                this.customImgData.title = '预览' + ' (' + i + '/' + len + ')'
                this.customImgData.initial = Number(i) - 1
                this.customImgData.list = list.map(item => {
                    return {
                        name: item.name,
                        url: this.$global.uploadUrl + item.url
                    }
                })
                this.customImgData.num = i - 1
                this.setActiveItem(i - 1)
            },
            setActiveItem(i) {
                if (this.$refs.carousel) {
                    this.$refs.carousel.setActiveItem(i)
                }
            },
            // 图片预览轮播切换
            handleCarousel(v) {
                this.customImgData.title = '预览' + ' (' + (Number(v) + 1) + '/' + this.customImgData.list.length + ')'
                this.customImgData.num = v
            },
            // 图片下载
            imgDownLoad() {
                window.open(this.customImgData.list[this.customImgData.num].url, "_blank");
            },
            //pageSize 改变时会触发
            handleSizeChange(val) {
                this.searchForm.limit = val
                this.getWorkReportList(this.searchForm)
            },
            //currentPage 改变时会触发
            handleCurrentChange(val) {
                this.searchForm.page = val
                this.getWorkReportList(this.searchForm)
            },
            updateTable() {
                this.toUpdateTableKey = !this.toUpdateTableKey
            }
        },
        beforeUpdate() {
            this.$nextTick(() => {
                this.$refs.tabList.doLayout()
            })
        }
    }
</script>

<style lang="less" scoped>
    .tableList {
        padding: 0 20px;
        code{
            font-family: sans-serif;
        }
        .gdbhStyle{
            color: #02b980;
            cursor: pointer;
        }
        .status {
            width: 28px;
            background-color: rgb(255, 59, 48);
            font-size: 12px;
            text-align: center;
            color: white;
            border-radius: 3px;
        }
    }

</style>